<!-- 新建子站点模态框 -->
<template>
  <a-form
    name="advanced_search"
    class="ant-advanced-search-form"
    :model="formState"
    ref="collectionForm"
    autoComplete="off"
  >
    <div class="titleSetting" style="margin-top: 24px">
      采集规则
      <a-tooltip placement="right">
        <template #title>仅采集此栏目已发布的内容</template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>

    <a-form-item
      :name="['collectionTime', 'value']"
      :label="formState.collectionTime.label"
      :rules="[formState.collectionTime.rule]"
    >
      <date-range-picker
        class="date-content"
        v-model:value="selectTimeRange"
        :showTime="false"
        :valueFormat="valueFormat"
      ></date-range-picker>
    </a-form-item>

    <div class="add-area">
      <a-form-item
        style="margin-bottom: 24px"
        :name="['columnCollection', 'value']"
        :label="formState.columnCollection.label"
        :rules="[formState.columnCollection.rule]"
        class="select-item"
      >
        <div class="select-box">
          <a-form-item-rest>
            <a-select
              style="width: 197px"
              v-model:value="formState.siteValue"
              placeholder="请选择站点"
              @change="changeSite"
              :options="formState.columnCollection.options.map((item: dataSourceType) => ({ value: item.id, label: item.siteName }))"
            ></a-select>
          </a-form-item-rest>
          <a-form-item-rest>
            <a-tree-select
              v-if="formState.siteValue"
              style="width: 197px; margin-left: 8px"
              v-model:value="formState.columnValue"
              ref="siteDetail_treeSelect"
              show-search
              :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
              placeholder="请选择栏目"
              allow-clear
              treeNodeFilterProp="channelName"
              :fieldNames="{
                children: 'children',
                label: 'channelName',
                value: 'id',
              }"
              tree-default-expand-all
              :tree-data="treeData"
              @change="changeContent"
              @click="clickContent"
            >
            </a-tree-select>
            <a-tooltip placement="right">
              <template #title>栏目添加上限为5条</template>
              <span class="iconfont icon-hint1 tips"></span>
            </a-tooltip>
          </a-form-item-rest>
        </div>
        <!-- <div class="help-msg">栏目添加上限为5条</div> -->
      </a-form-item>
      <div v-for="(item, index) in formState.columnCollectionList" :key="index">
        <a-form-item
          class="otherFormItems"
          :name="['columnCollectionList', index, 'value']"
          :rules="[item.rule]"
        >
          <div class="select-box-item">
            <a-form-item-rest>
              <a-select
                style="width: 182px"
                v-model:value="item.site"
                placeholder="请选择站点"
                @change="changeSiteList"
                :options="formState.columnCollection.options.map((item: dataSourceType) => ({ value: item.id, label: item.siteName }))"
              ></a-select>
            </a-form-item-rest>
            <a-form-item-rest v-if="item.site">
              <a-tree-select
                style="width: 182px; margin-left: 8px"
                placeholder="请选择栏目"
                v-model:value="item.column"
                ref="usermanage_treeSelect"
                show-search
                :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
                allow-clear
                treeNodeFilterProp="name"
                :fieldNames="{
                  children: 'children',
                  label: 'channelName',
                  value: 'id',
                }"
                tree-default-expand-all
                :tree-data="treeDataList[index]"
                @change="changeContentList(index, item)"
                @click="clickContentList(item, index)"
              >
              </a-tree-select>
            </a-form-item-rest>
            <i class="iconfont i-delete" @click="deleteColumnCollectionList(index)"
              >&#xe8e2;</i
            >
          </div>
        </a-form-item>
      </div>

      <div
        class="add-new"
        :class="
          formState.columnCollectionList.length <= 0
            ? 'hidd-margin'
            : formState.columnCollectionList.length >= 4
            ? 'noadd'
            : ''
        "
        @click="addColumnCollectionList"
      >
        新增栏目
      </div>
    </div>
    <div class="add-area">
      <a-form-item
        :name="['titleSelect', 'value']"
        :label="formState.titleSelect.label"
        :rules="[formState.titleSelect.rule]"
        class="select-item"
      >
        <a-input
          v-model:value="formState.titleSelect.value"
          @change="changeTitle"
          :placeholder="formState.titleSelect.placeholder"
          :allow-clear="formState.titleSelect.value"
        />
        <a-tooltip placement="right">
          <template #title>标题添加上限为5条</template>
          <span class="iconfont icon-hint1 tips"></span>
        </a-tooltip>
        <!-- <div class="help-msg">标题添加上限为5条</div> -->
      </a-form-item>

      <template v-for="(item, index) in formState.titleStrList" :key="index">
        <a-form-item
          class="otherFormItems"
          :name="['titleStrList', index, 'value']"
          :rules="[item.rule]"
        >
          <a-input-group compact class="otherSiteProtocols">
            <a-input
              v-model:value="item.value"
              show-count
              :maxlength="25"
              :allow-clear="item.value"
              @focus=""
              class="titleStrList-input"
            />
            <i class="iconfont i-delete" @click="deleteTitleStrList(index)">&#xe8e2;</i>
          </a-input-group>
        </a-form-item>
      </template>

      <div
        class="add-new"
        :class="
          formState.titleStrList.length <= 0
            ? 'hidd-margin'
            : formState.titleStrList.length >= 4
            ? 'noadd'
            : ''
        "
        @click="addTitleStrList"
      >
        新增标题
      </div>
    </div>

    <div class="titleSetting" style="margin-top: 40px">站点规则</div>
    <a-form-item
      :name="['collectionType', 'value']"
      :label="formState.collectionType.label"
      :rules="[formState.collectionType.rule]"
      class="channelCopyOptions"
    >
      <a-radio-group v-model:value="formState.collectionType.value">
        <a-radio :value="1">复制</a-radio>
        <a-radio :value="2">链接引用</a-radio>
        <a-radio :value="3">镜像引用</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item
      :name="['contentStatus', 'value']"
      :label="formState.contentStatus.label"
      :rules="[formState.contentStatus.rule]"
      class="channelCopyOptions"
      v-if="formState.collectionType.value != 2"
    >
      <a-radio-group v-model:value="formState.contentStatus.value">
        <a-radio :value="1">草稿</a-radio>
        <a-radio :value="5">已发布</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item
      :name="['collectionStatus', 'value']"
      :label="formState.collectionStatus.label"
      :rules="[formState.collectionStatus.rule]"
      class="channelCopyOptions"
    >
      <a-radio-group v-model:value="formState.collectionStatus.value">
        <a-radio :value="true">开启</a-radio>
        <a-radio :value="false">关闭</a-radio>
      </a-radio-group>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from "vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import request from "@/api/index";
// import { checkCreatSiteForm, detectKey } from "./formRuler";
import dateRangePicker from "@/components/picker/dateRangePicker.vue";
import getOptions from "@/utils/getRelationOptions";
import { useRoute } from "vue-router";
interface dataSourceType {
  [propName: string]: any;
}
// props
const props = defineProps({
  collectionState: {
    type: Object,
    default: {},
  },
  parentTitle: {
    type: [String, Number],
    default: "",
  },
  channelId: {
    type: Number,
    default: 0,
  },
  parentId: {
    type: [String, Number],
    default: "",
  },
});
//emit
const emit = defineEmits(["checkSetTime"]);
//data
const valueFormat = ref("YYYY-MM-DD");
// baseInfo - 从详情页传来
const route: any = useRoute();
const selectTimeRange = ref<(string | number)[]>([]);
const singleCol = ref<any[]>([]);
const mulCol = ref<any[]>([]);
const otherSiteProtocolsList = ref<dataSourceType[]>([]);
const treeData = ref<any>([]);
const treeDataList = ref<any>([]);
const siteData = ref<dataSourceType[]>([]);
const siteDataList = ref<any[]>([]);
let uniqueCheck = reactive<dataSourceType>({});

const checkCreatSiteForm = async (_rule: dataSourceType = {}, value: any) => {
  if (_rule.required) {
    // 必填项验证非空并排除非必须项
    if (!value) {
      return Promise.reject(`${_rule.msg1}`);
    } else {
      return Promise.resolve();
    }
  }
};

const formState = reactive<dataSourceType>({
  collectionTime: {
    value: "",
    rule: {
      required: false,
      trigger: ["blur"],
      message: "",
      key: "sitePath",
      params: uniqueCheck,
    },
    placeholder: "请输入",
    label: "采集时间",
  },
  titleStrList: <dataSourceType[]>[],
  columnCollectionList: <dataSourceType[]>[],
  channelSiteDtoList: <dataSourceType[]>[],
  siteValue: undefined,
  columnValue: [],
  description: {
    value: "",
    label: "站点描述",
    placeholder: "不超过500个字",
  },
  titleSelect: {
    value: "",
    rule: {
      required: false,
      trigger: ["change"],
      message: "",
      api: "",
      params: {},
    },
    placeholder: "请输入内容标题",
    label: "标题筛选",
  },
  columnCollection: {
    value: false,
    rule: {
      required: true,
      validator: checkCreatSiteForm,
      trigger: ["change", "bulr"],
      msg1: "请选择站点及栏目！",
    },
    options: [],
    label: "栏目采集",
  },
  collectionType: {
    value: 1,
    rule: {
      required: true,
      //validator: checkCreatSiteForm,
      //trigger: ["change"],
      message: "请选择",
      //api: "",
      //params: {}
    },
    label: "采集方式",
  },
  contentStatus: {
    value: 5,
    rule: {
      required: true,
      //validator: checkCreatSiteForm,
      //trigger: ["change"],
      message: "请选择！",
      //api: "",
      //params: {}
    },
    label: "状态设置",
  },
  collectionStatus: {
    value: true,
    rule: {
      required: true,
      //validator: checkCreatSiteForm,
      //trigger: ["change"],
      message: "请选择！",
      //api: "",
      //params: {}
    },
    label: "采集设置",
  },
});

const collectionForm = ref<any>(null); //整个form的ref，需要暴露到父组件
const channelSiteDtoList = ref<dataSourceType[]>([]);
const titleStrList = ref<dataSourceType[]>([]);
let formParams = reactive<dataSourceType>({});

formParams = computed(() => {
  return {
    channelId: props.channelId,
    channelSiteDtoList: channelSiteDtoList.value,
    endTime: selectTimeRange.value ? selectTimeRange.value[1] : null,
    startTime: selectTimeRange.value ? selectTimeRange.value[0] : null,
    // "columnCollection": formState.columnCollection.value,
    collectionType: formState.collectionType.value,
    contentStatus: formState.contentStatus.value,
    collectionStatus: formState.collectionStatus.value,
    titleStrList: titleStrList.value,
  };
});

//methods
const getCurrentData = () => {
  return new Date().toLocaleDateString();
};

const addTitleStrList = () => {
  // 添加标题
  if (formState.titleStrList.length >= 4) return;
  formState.titleStrList.push({
    value: "",
    rule: {
      required: false,
      //validator: checkSiteDomainAlias,
      trigger: ["blur"],
      msg1: "填写",
      msg2: "",
      api: "",
      key: "titleStrList",
      params: {},
    },
    placeholder: "请输入",
    label: "",
  });
};

const addColumnCollectionList = () => {
  // 添加栏目
  if (formState.columnCollectionList.length >= 4) return;
  formState.columnCollectionList.push({
    value: "",
    site: "",
    column: [],
    rule: {
      required: false,
      // validator: checkSiteDomainAlias,
      trigger: ["blur"],
      msg1: "111",
      msg2: "222",
      api: "fetchsiteManageTabledDataUniqueCheck",
      key: "columnCollectionList",
      params: {},
    },
    placeholder: "请输入",
    label: "",
  });
};

const deleteColumnCollectionList = (index: number) => {
  formState.columnCollectionList.splice(index, 1);
  mulCol.value[index] && mulCol.value.splice(index, 1);
  channelSiteDtoList.value = [...singleCol.value, ...mulCol.value];
};
const deleteTitleStrList = (index: number) => {
  formState.titleStrList.splice(index, 1);
  titleStrList.value[index] && titleStrList.value.splice(index, 1);
};

//选择栏目
const changeContent = () => {
  let arr: dataSourceType[] = [];
  let obj: dataSourceType = {};
  obj.channelId = formState.columnValue;
  obj.siteId = formState.siteValue;
  arr.push(obj);
  singleCol.value = arr;
  channelSiteDtoList.value = [...singleCol.value, ...mulCol.value];
  formState.columnCollection.value = !!(formState.siteValue && formState.columnValue);
};
//选择栏目列表
const changeContentList = (index: number, item: any) => {
  if (!mulCol.value[index]) {
    let obj: dataSourceType = {};
    obj.channelId = item.column || item.channelId;
    obj.siteId = item.site || item.siteId;
    mulCol.value.push(obj);
    channelSiteDtoList.value = [...singleCol.value, ...mulCol.value];
  } else if (mulCol.value[index]) {
    mulCol.value[index].channelId = item.column || item.channelId;
    mulCol.value[index].siteId = item.site || item.siteId;
  }
  channelSiteDtoList.value = [...singleCol.value, ...mulCol.value];
  formState.columnCollection.value = !!(formState.siteValue && formState.columnValue);
};

//点击获取站点
const clickContent = () => {
  fetchChannelListBySiteId(formState.siteValue, 1);
};
//点击获取站点
const clickContentList = (item: any, index: number) => {
  fetchChannelListBySiteId(item.site, 2, index);
};

//输入标题
const changeTitle = (e: any) => {
  if (e.target.value.length) {
    titleStrList.value = [e.target.value];
  }
};

//站点变动
const changeSite = (e: any) => {
  formState.columnValue = null;
};

//站点变动
const changeSiteList = (e: any) => {};

const loopGetId = (arr: any[]) => {
  arr.length &&
    arr.forEach((item: any) => {
      if (item.id === route.query.channelId) {
        item.disabled = true;
      } else if (item.children && item.children.length) {
        loopGetId(item.children);
      }
    });
};

const fetchChannelListBySiteId = async (
  siteId: number | string,
  type: number,
  index?: any
) => {
  const postData = {
    siteId,
    allPermFilter: false,
  };
  const list = (await request.fetchChannelListBySiteId(postData)) as any;
  if (type === 1) {
    siteData.value = list;
    loopGetId(siteData.value);
    treeData.value = getOptions(route.query.channelId, siteData.value);
  } else {
    siteDataList.value[index] = list;
    loopGetId(siteDataList.value[index]);
    treeDataList.value[index] = getOptions(
      route.query.channelId,
      siteDataList.value[index]
    );
  }
};

//获取全部站点
const fetchContentAllSiteList = async () => {
  formState.columnCollection.options = await request.fetchContentAllSiteList();
};

// watch
watch(
  () => formState.titleStrList,
  (newVal, oldVal) => {
    let arr: string[] = [];
    newVal.forEach((item: any) => {
      item ? arr.push(item.value) : "";
    });
    titleStrList.value = formState.titleSelect.value
      ? [formState.titleSelect.value, ...arr]
      : arr;
  },
  { deep: true }
);
const getDates = () => {
  var lw = new Date(); // 获取时间
  var lastY = lw.getFullYear();
  var lastM = lw.getMonth() + 1;
  var lastD = lw.getDate();
  var startdate =
    lastY +
    "-" +
    (lastM < 10 ? "0" + lastM : lastM) +
    "-" +
    (lastD < 10 ? "0" + lastD : lastD);

  selectTimeRange.value[0] = startdate;
  selectTimeRange.value[1] = startdate;
};
watch(
  () => props.collectionState,
  (newVal: dataSourceType, oldVal) => {
    if (JSON.stringify(newVal) == "{}") {
      getDates();
    }
    if (JSON.stringify(newVal) != JSON.stringify(oldVal)) {
      let keys = Object.keys(newVal);
      formState.titleStrList = [];
      formState.columnCollectionList = [];
      for (const i of keys) {
        if (formState.hasOwnProperty(i)) {
          if (i == "titleStrList" && newVal[i].length) {
            newVal[i].forEach((item: any, index: number) => {
              formState.titleSelect.value = newVal[i][0];
              if (index <= 0) {
                formState.titleSelect.value = item;
              } else {
                formState.titleStrList.push({
                  value: item,
                  rule: {
                    required: false,
                    //validator: checkSiteDomainAlias,
                    trigger: ["blur"],
                    msg1: "111",
                    msg2: "222",
                    api: "",
                    key: "titleStrList",
                    params: {},
                    value: item,
                  },
                  placeholder: "请输入",
                  label: "",
                });
              }
            });
          }
          if (i == "columnCollectionList" && newVal[i].length) {
            newVal[i].forEach((item: any, index: number) => {
              if (index <= 0) {
                formState.siteValue = item.siteId;
                formState.columnValue = item.channelId;
              } else {
                formState.columnCollectionList.push({
                  value: "",
                  site: item.siteId,
                  column: item.channelId,
                  rule: {
                    required: false,
                    // validator: checkSiteDomainAlias,
                    trigger: ["blur"],
                    msg1: "111",
                    msg2: "222",
                    api: "fetchsiteManageTabledDataUniqueCheck",
                    key: "columnCollectionList",
                    params: {},
                  },
                  placeholder: "请输入",
                  label: "",
                });
              }
            });
          }
          if (i == "channelSiteDtoList" && newVal[i].length) {
            newVal[i].forEach((item: any, index: number) => {
              if (index === 0) {
                fetchChannelListBySiteId(item.siteId, 1);
                formState.siteValue = item.siteId;
                formState.columnValue = item.channelId;
                changeContent();
              } else {
                fetchChannelListBySiteId(item.siteId, 2, index - 1);
                changeContentList(index - 1, item);
                formState.columnCollectionList.push({
                  value: "",
                  site: item.siteId,
                  column: item.channelId,
                  rule: {
                    required: false,
                    // validator: checkSiteDomainAlias,
                    trigger: ["blur"],
                    msg1: "111",
                    msg2: "222",
                    api: "fetchsiteManageTabledDataUniqueCheck",
                    key: "columnCollectionList",
                    params: {},
                  },
                  placeholder: "请输入",
                  label: "",
                });
              }
            });
          }
          formState[i].value = newVal[i];
        } else {
          if (i == "endTime") {
            if (!newVal[i]) {
              getDates();
            } else {
              selectTimeRange.value[1] = newVal[i];
            }
          }
          if (i == "startTime") {
            selectTimeRange.value[0] = newVal[i];
          }

          //formState[i].rule ? formState[i].rule.value = newVal[i] : '';
        }
      }
    }
  },
  { deep: true, immediate: true }
);

//onMounted
onMounted(() => {
  fetchContentAllSiteList();
});

//暴漏组件方法
// defineExpose //把子组件中的方法或变量暴漏给父组件
defineExpose({ collectionForm, formParams, formState });
</script>

<style lang="less" scoped>
.ant-advanced-search-form {
  height: calc(100% - 24px);
  overflow: auto;
  padding-left: 24px;
}

.otherSiteProtocols {
  margin-top: 16px;
}

.select-box {
  margin-top: 0px;
}

.select-box-item {
  margin-top: 16px;
}

.add-new {
  display: flex;
  flex-direction: row;
  justify-content: end;
  margin-top: 8px;
  margin-bottom: 24px;
  display: flex;
  width: 486px;
  height: 14px;
  font-size: 14px;
  font-weight: 400;
  color: var(--theme_text_hightlight_color, #1f6ded);
  line-height: 14px;
  margin-top: 8px;
  text-align: right;
  cursor: pointer;
}

.help-msg {
  margin-top: 8px;
  font-size: 12px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
  line-height: 20px;
}

.noadd {
  color: rgba(0, 0, 0, 0.25);
}

.addSiteDomain:hover {
  color: var(--theme_button_hover_bg_color, #1f6ded);
}

.addSiteDomain:active {
  color: var(--theme_button_active_bg_color, #1f6ded);
}

.addSiteDomain_maringTop {
  margin-top: -16px;
  margin-bottom: 18px;
}

.otherFormItems {
  padding-left: 83px;
  margin-bottom: 0px;
}

.i-delete {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  line-height: 32px;
  margin-left: 12px;
}

.i-delete:hover {
  cursor: pointer;
  color: rgba(0, 0, 0, 0.85);
}

.siteDomain {
  margin-bottom: 0px;
}

.description,
.status {
  margin-bottom: 12px;
}

.setTime {
  font-size: 14px;
  font-weight: 400;
  color: #1f6ded;
  margin-left: 24px;
  cursor: pointer;
}

.date-content {
  width: 254px;
}

.channelCopyOptions {
  margin-bottom: 8px !important;
}

.select-item {
  margin-bottom: 0px !important;
}

.add-area {
  position: relative;
  margin-bottom: 24px;

  .hidd-margin {
    position: absolute;
    top: 33px;
    left: 0;
  }
}

:deep(.ant-form-item) {
  width: 592px;
  display: flex;

  .ant-form-item-control {
    width: 505px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 83px;
    text-align: right;
  }
}

::v-deep(.ant-form) {
  line-height: 1;
}

::v-deep(.siteDomain-input) {
  width: 399px;
}

// ::v-deep(.ant-form-item:nth-of-type(1)) {
//   margin-left: 0px;
//   margin-top: -8px;
//   margin-bottom: 24px;
// }

::v-deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
  margin-bottom: 10px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 400px;
}

::v-deep(.ant-input-affix-wrapper:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

::v-deep(.ant-input-affix-wrapper:focus) {
  .anticon-close-circle {
    display: none;
  }

  .ant-input-show-count-suffix {
    display: block;
  }
}

::v-deep(.titleStrList-input) {
  width: 371px;
}

::v-deep(.ant-input-affix-wrapper-textarea-with-clear-btn) {
  min-height: 80px;
  position: relative;
}

::v-deep(.ant-input-textarea-show-count) {
  position: relative;
}

::v-deep(.ant-input-textarea-show-count::after) {
  position: absolute;
  right: 12px;
  bottom: 26px;
  line-height: 1;
}

::v-deep(.ant-radio-group) {
  margin-top: 5px;
}

::v-deep(.ant-radio-wrapper:nth-child(1)) {
  margin-bottom: 12px;
}

.titleSetting {
  height: 40px;
  font-size: 14px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  line-height: 40px;
  background: #f7f8fa;
  border-radius: 2px 2px 2px 2px;
  margin-bottom: 18px;
  position: relative;
  padding-left: 24px;
}

.titleSetting::after {
  width: 3px;
  height: 12px;
  background: #1f6ded;
  border-radius: 0px 0px 0px 0px;
  opacity: 1;
  content: "";
  position: absolute;
  left: 12px;
  z-index: 1;
  top: 14px;
}

.tips {
  margin-left: 8px;
}
</style>
